<template>
  <div>
    <!-- 查询窗口 -->
    <el-form
      ref="queryForm"
      :model="queryParams"
      class="form"
    >
      <el-row :gutter="20">
        <el-col :span="7.5">
          <el-form-item
            :label="$t('trade_promotion_promotion_500')"
            size="small"
            prop="type"
            label-width="50px"
          >
            <el-select
              v-model="queryParams.type"
              :placeholder="$t('trade_promotion_promotion_501')"
              clearable
            >
              <el-option
                v-for="item in promotionTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="7.5">
          <el-form-item
            :label="$t('trade_promotion_promotion_502')"
            size="small"
            prop="categoryName"
            label-width="250px"
          >
            <div class="block">
              <el-cascader
                v-model="queryParams.categoryName"
                :options="categoryOptions"
                :props="{ expandTrigger: 'hover', multiple: false, checkStrictly: true }"
                clearable
              />
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="7.5">
          <el-form-item
            :label="$t('trade_promotion_promotion_503')"
            size="small"
            prop="status"
            label-width="50px"
          >
            <el-select
              v-model="queryParams.status"
              :placeholder="$t('trade_promotion_promotion_501')"
              clearable
            >
              <el-option
                v-for="item in statusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="14">
          <el-form-item size="small">
            <el-button
              type="primary"
              style="width: 120px;font-size:13px;margin-left: 12px"
              @click="handleQuery"
            >{{$t('trade_promotion_promotion_504')}}</el-button>
            <el-button
              type="primary"
              style="width: 120px;font-size:13px;margin-left: 30px"
              @click="resetQuery"
            >{{$t('trade_promotion_promotion_505')}}</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <!-- 按钮 -->
    <el-row :gutter="20">
      <el-col :span="20">
        <el-button
          class="insertButton"
          type="success"
          style="width:150px"
          @click="handleAdd"
        >{{$t('trade_promotion_promotion_506')}}</el-button>
        <el-button
          class="enableAllButton"
          :disabled="multiple"
          @click="handleEnable"
        >{{$t('trade_promotion_promotion_507')}}</el-button>
        <el-button
          class="disableAllButton"
          type="info"
          :disabled="multiple"
          @click="handleDisable"
        >{{$t('trade_promotion_promotion_508')}}</el-button>
        <el-button
          type="danger"
          :disabled="multiple"
          class="deletesButton"
          @click="handleDelete"
        >{{$t('trade_promotion_promotion_509')}}</el-button>
      </el-col>
    </el-row>
    <!-- 数据展示Table -->
    <el-table
      v-loading="loading"
      border
      :data="dataList"
      style="border: 1px solid rgb(211 211 211); margin-left: 20px; width: 96%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        width="60"
        align="center"
      />
      <el-table-column
        type="index"
        width="120"
        :label="$t('trade_promotion_promotion_510')"
        align="center"
      />
      <el-table-column
        :label="$t('trade_promotion_promotion_511')"
        align="center"
        prop="type"
        width="130"
      >
        <template slot-scope="scope">
          <span>{{ getTypeLabel(scope.row.type) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('trade_promotion_promotion_512')"
        align="center"
        prop="threshold"
        width="110"
      />
      <el-table-column
        :label="$t('trade_promotion_promotion_513')"
        align="center"
        prop="amount"
        width="120"
      />
      <el-table-column
        :label="$t('trade_promotion_promotion_514')"
        align="center"
        prop="categoryNames"
        width="150"
      >
        <template slot-scope="scope">
          <span v-if="scope.row.categoryNames">{{ scope.row.categoryNames }}</span>
          <span v-else>{{$t('trade_promotion_promotion_515')}}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('trade_promotion_promotion_516')"
        align="center"
        prop="description"
        width="180"
      />
      <el-table-column
        :label="$t('trade_promotion_promotion_503')"
        align="center"
        prop="status"
        width="130"
      >
        <template slot-scope="scope">
          <span v-if="scope.row.status == 1">{{$t('trade_promotion_promotion_517')}}</span>
          <span v-else>{{$t('trade_promotion_promotion_518')}}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('trade_promotion_promotion_519')"
        align="center"
      >
        <template slot-scope="scope">
          <el-button
            size="small"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >{{$t('trade_promotion_promotion_520')}}</el-button>
          <el-button
            size="small"
            type="text"
            icon="el-icon-circle-close"
            @click="handleChange(scope.row)"
          >
            {{ scope.row.status === 1 ? $t('trade_promotion_promotion_518') : $t('trade_promotion_promotion_521') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页加载 -->
    <el-pagination
      :current-page="showAllParams.current"
      :page-sizes="[5, 10, 20]"
      :page-size="showAllParams.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      class="page"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <!-- 新增/修改弹窗，默认不显示 -->
    <el-dialog
      center
      :title="title"
      :visible.sync="addOpen"
      width="500px"
      append-to-body
      :before-close="clearForm"
    >
      <el-form
        ref="newPromotion"
        :model="newPromotion"
        :rules="rules"
        label-width="120px"
        :label-position="labelPosition"
      >
        <el-form-item
          :label="$t('trade_promotion_promotion_511')"
          prop="type"
        >
          <el-select
            v-model="newPromotion.type"
            :placeholder="$t('trade_promotion_promotion_501')"
            class="uniform-width"
          >
            <el-option
              v-for="item in promotionTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          :label="$t('trade_promotion_promotion_512')"
          prop="threshold"
        >
          <el-input
            v-model.number="newPromotion.threshold"
            type="number"
            class="uniform-width"
          />
        </el-form-item>
        <el-form-item
          :label="$t('trade_promotion_promotion_513')"
          prop="amount"
        >
          <el-input
            v-model.number="newPromotion.amount"
            type="number"
            class="uniform-width"
          />
        </el-form-item>
        <el-form-item
          :label="$t('trade_promotion_promotion_502')"
          prop="categoryNames"
          label-width="120px"
        >
          <div class="block">
            <el-cascader
              v-model="newPromotion.categoryNames"
              :options="categoryOptions"
              :disabled="categoryDisabled"
              :props="{ expandTrigger: 'hover', multiple: true, checkStrictly: true }"
              clearable
              class="uniform-width"
            />
          </div>
        </el-form-item>
        <el-form-item
          :label="$t('trade_promotion_promotion_503')"
          prop="status"
        >
          <el-radio
            v-model="newPromotion.status"
            label="1"
          >{{$t('trade_promotion_promotion_521')}}</el-radio>
          <el-radio
            v-model="newPromotion.status"
            label="2"
          >{{$t('trade_promotion_promotion_518')}}</el-radio>
        </el-form-item>
        <el-form-item
          :label="$t('trade_promotion_promotion_516')"
          prop="description"
        >
          <el-input
            v-model="newPromotion.description"
            type="textarea"
            :rows="2"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>
        <el-form-item>
          <el-button
            class="submitAddButton"
            @click="submitAddForm"
          >
            {{ buttonTitle }}
          </el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import {
  queryPromotion,
  updateStatus,
  updateManyStatus,
  deleteManyPromotion,
  addPromotion,
  updatePromotion
} from "@/api/promotion";
import { queryCategoryTree } from '@/api/category'
export default {
  data() {
    return {
      // 表单标签对齐方式
      labelPosition: 'left',
      // 是否显示弹出层
      // 弹窗
      title:"",
      buttonTitle:"",
      addOpen:false,
      // 遮罩层
      loading: false,
      // 总条数
      total:0,
      // 表格数据
      dataList: [],
      // 查询参数
      queryParams: {
        current: 1,
        size: 10,
        categoryName:null,
        status:null,
        type: null,
      },
      // 类别选择框
      categoryDisabled:true,
      // 新增优惠
      newPromotion:{
        description:"",
        type:null,
        threshold:null,
        amount:null,
        categoryIds:null,
        status:'1',
        categoryNames:null
      },
      // 勾选1个或多个
      multiple: true,
            // 展示所有类别参数
      showAllParams: {
        current: 1,
        pageSize: 10,
      },
      // 批量修改优惠状态参数
      updateManyStatus:{
        status:null,
        promotionIds:[]
      },
      // 批量删除优惠状态数组
      deleteManyPromotionId:[],
      // 下拉框选项数据
      promotionTypeOptions: [
        {
          value: 1,
          label: this.$t('trade_promotion_promotion_522'),
        },
        {
          value: 2,
          label: this.$t('trade_promotion_promotion_523'),
        },
        {
          value:3,
          label:this.$t('trade_promotion_promotion_524')
        }
      ],
      statusOptions:[
                {
          value: "1",
          label: this.$t('trade_promotion_promotion_517'),
        },
        {
          value: "2",
          label: this.$t('trade_promotion_promotion_525'),
        },
      ],
      categoryOptions:[],
      // 非单个禁用
      single: true,
      // 表单校验
      rules: {
        type: [
          { required: true, message: this.$t('trade_promotion_promotion_526'), trigger: 'change' },
        ],
        threshold: [
          { required: true, message: this.$t('trade_promotion_promotion_527'), trigger: 'blur' },
          { type: 'number', message: this.$t('trade_promotion_promotion_528'), trigger: 'blur' },
          { validator: this.validateThreshold, trigger: 'blur' },
        ],
        amount: [
          { required: true, message: this.$t('trade_promotion_promotion_529'), trigger: 'blur' },
          { type: 'number', message: this.$t('trade_promotion_promotion_528'), trigger: 'blur' },
          { validator: this.validateAmount, trigger: 'blur' },
        ],
        categoryNames: [
          { validator: this.validateCategoryName, trigger: 'change' },
        ],
        description: [
          { required: true, message: this.$t('trade_promotion_promotion_530'), trigger: "blur" },
        ],
      },
    }
  },
  watch: {
    // 监听newPromotion.type的变化，并据此设置categoryDisabled的值
    'newPromotion.type'(newVal) {
      this.categoryDisabled = newVal !== 3; // 如果不是类别折扣，则禁用
    }
  },
  created() {
    this.getAll()
    queryCategoryTree().then(res => {
      this.categoryOptions = res.data
      // 进一步处理value为label
      this.categoryOptions.forEach(first => {
        first.value = first.label
        first.children.forEach(second => {
          second.value = second.label
        })
      })
    })
  },
  methods:{
    /** 获取所有优惠 */
    getAll(){
      this.loading = true;
      queryPromotion(this.showAllParams).then((response) => {
        this.dataList = response.data.records;
        this.total = Number(response.data.total);
        this.loading = false;
      });
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.$refs.queryForm.resetFields()
      this.queryParams.categoryName=null
      this.queryParams.status=null
      this.queryParams.type=null
      this.getAll();
    },
    clearForm(){
      this.addOpen=false;
      this.$refs.newPromotion.resetFields()
      this.newPromotion.description=""
      this.newPromotion.type=null,
      this.newPromotion.threshold=null,
      this.newPromotion.amount=null,
      this.newPromotion.categoryIds=null,
      this.newPromotion.status='1',
      this.newPromotion.categoryNames=null

    },
    // 转换优惠类型显示方式
    getTypeLabel(type) {
      const option = this.promotionTypeOptions.find(item => item.value === type);
      return option ? option.label : '未知';
    },
    /** 搜索按钮操作 */
    handleQuery() {
      const queryParams = { ...this.queryParams }
      const flattened = this._.flatten(this.queryParams.categoryName);
      queryParams.categoryName = flattened.length > 0 ? flattened[flattened.length - 1] : null;
      queryPromotion(queryParams).then((response) => {
        this.dataList = response.data.records;
        this.total = Number(response.data.total);
        this.loading = false;
      });

    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.updateManyStatus.promotionIds = selection.map((item) => Number(item.id));
      this.deleteManyPromotionId = selection.map((item) => Number(item.id));
      this.single = selection.length !== 1;
      this.multiple = !(selection.length>=1);
    },
    /** 处理分页 */
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.queryParams.current = val;
      this.getList();
    },
    /** 改变一行优惠状态 */
    handleChange(row){
      const newStatus = row.status === 1 ? 2 : 1; // 切换状态值
      updateStatus(row.id,newStatus).then((response) => {
        this.dataList = this.dataList.map(item => {
        if (item.id === row.id) {
          // 更新status值和操作列按钮的显示文本
          item.status = newStatus;
          return item;
        }
        return item;
      });
        this.$message.success(response.data);

      });
    },
    /** 批量删除 */
    handleDelete(){
      deleteManyPromotion(this.deleteManyPromotionId).then((response) => {
        this.$message.success(response.data===1?'批量删除成功':'删除失败');
        this.getAll()
        this.deleteManyPromotionId=[]
      });
    },
    /** 批量禁用 */
    handleDisable(){
      this.updateManyStatus.status=2
      updateManyStatus(this.updateManyStatus).then((response) => {
        this.$message.success(response.data===1?'批量禁用成功':'禁用失败');
        this.getAll()
        this.updateManyStatus={}
      });
    },
    /** 批量启用 */
    handleEnable(){
      this.updateManyStatus.status=1
      updateManyStatus(this.updateManyStatus).then((response) => {
        this.$message.success(response.data===1?'批量启用成功':'启用失败');
         this.getAll()
         this.updateManyStatus={}
      });
    },
    // 验证表单
    validateAmount(rule, value, callback) {
      const type = this.newPromotion.type;
      if (type === 2) {
        if (value < 0 || value > 1) {
          callback(new Error('折扣率必须在0到1之间'));
        } else {
          callback();
        }
      } else if (type === 1) {
        if (value < 0) {
          callback(new Error('满减值必须大于等于0'));
        } else {
          callback();
        }
      }
      else if (type === 3) {
        if (value < 0 || value > 1) {
          callback(new Error('折扣率必须在0到1之间'));
        } else {
          callback();
        }
      }
      else {
        callback(new Error('请先选择优惠类型'));
      }
    },
    validateThreshold(rule, value, callback) {
    if (Number(value) < 0) {
      callback(new Error('触发值必须是一个大于等于0的数'));
    } else {
      callback();
    }
    },
    validateCategoryName(rule, value, callback) {
      const type = this.newPromotion.type;
      if (type !== '3')
        return callback();
      if (!value || value.length === 0)
        return callback(new Error('请选择折扣商品类别'));
      callback();
    },
    /** 新增优惠 */
    handleAdd(){
      this.addOpen=true;
      this.title="新增优惠"
      this.buttonTitle="确认新增"
    },
    /** 修改优惠 */
    handleUpdate(row){
      this.addOpen=true;
      this.title="修改优惠";
      this.buttonTitle="确认修改"
      // console.log(row)
      this.newPromotion = {
        id:row.id,
        description: row.description,
        status: row.status.toString(),
        type: Number(row.type),
        threshold:row.threshold,
        amount:row.amount,
      }
      // 清洗表格数据，把json格式变为list格式
      this.newPromotion.categoryNames = JSON.parse(row.categoryNames).map(item => item.replace(/"/g, ''));
      // 根据categoryNames构建路径数组，以便选中
      this.newPromotion.categoryNames=this.buildPaths(this.categoryOptions, row.categoryNames)
    },
    /** 提交修改/新增优惠表单 */
    submitAddForm(){
      this.$refs["newPromotion"].validate((valid) => {
        if (valid) {
        // this.newPromotion.type=Number(this.newPromotion.type)
        // this.newPromotion.status=Number(this.newPromotion.status)
        if (this.newPromotion.categoryNames && Array.isArray(this.newPromotion.categoryNames))
          this.newPromotion.categoryNames=JSON.stringify(this.newPromotion.categoryNames.map(subarray => subarray[subarray.length - 1]))
          if(this.title=="新增优惠"){
            addPromotion(this.newPromotion).then((response) => {
            this.$message.success(response.data===1?'新增优惠成功':'新增失败')
            this.$refs.newPromotion.resetFields()
            this.newPromotion={}
            this.newPromotion.status="1"
            this.getAll()
            this.addOpen=false
            });
          }
          else if(this.title=="修改优惠"){
            // console.log(this.newPromotion)
            updatePromotion(this.newPromotion).then((response) => {
              this.$message.success(response.data===1?'修改优惠成功':'修改失败')
              this.$refs.newPromotion.resetFields()
              this.newPromotion={}
              this.newPromotion.status="1"
              this.getAll()
              this.addOpen=false
              });
          }
        }
      });
    },
    /** 构建路径数组 */
    buildPaths(options, selectedValues) {
    const paths = [];
    function traverse(currentOption, currentPath = []) {
      if (selectedValues.includes(currentOption.value)) {
        // 如果当前选项是需要选中的值，则将其路径添加到paths中
        paths.push([...currentPath, currentOption.value]);
      }
      if (currentOption.children) {
        // 如果有子选项，则递归遍历子选项
        currentOption.children.forEach(child => {
          traverse(child, [...currentPath, currentOption.value]);
        });
      }
    }
    // 遍历所有顶级选项
    options.forEach(option => {
      traverse(option);
    });
    return paths;
  }
  }
}
</script>

<style>
.form {
  border: 2px dashed rgb(211, 211, 211);
  padding: 20px;
  padding-bottom: 0px;
  margin: 10px 20px 20px 20px;
}
.page {
  margin-top: 5px;
  margin-left: 280px;
}
.insertButton,.insertButton:hover{
    margin-left: 20px;
  width: 120px;
}
.enableAllButton:disabled,.enableAllButton:disabled:hover{
  width: 120px;
  background-color: #93cbd1;
  color:white;
  margin-bottom: 10px;
}
.enableAllButton,.enableAllButton:hover{
  width: 120px;
  background-color: #4ac1cd;
  color:white;
  margin-bottom: 10px;
}
.enableAllButton:hover{
  background-color: #93cbd1;
}
.disableAllButton,.disableAllButton:hover{
  width: 120px;
}
.deletesButton,.deletesButton:hover{
  width:120px;
}
.submitAddButton,.submitAddButton:hover{
  width:180px;
  margin-left: 10px;
  color:white;
  background-color: #DA8F0C;
}
.submitAddButton:hover{
  background-color: #d6a34b;
}
.uniform-width{
  width:330px;
}
</style>
